<template>
	<view>
		<map ref="map" id="map" :style="{width: '750rpx', height: windowHeight + 'rpx'}" :latitude="centerY" :longitude="centerX"
		 :markers="markers" :show-location="true" :scale="scale">
		</map>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				windowHeight: 1200,
				userData: [],
				centerX: 104.052012,
				centerY: 30.689514,
				markers: [],
				scale: 15
			}
		},
		onLoad(option) {
			this.centerX = this.$utils.getData("centerX")
			this.centerY = this.$utils.getData("centerY")
		},
		onShow() {
			uni.checkSession({
				success: function(res) {},
				fail: function(res) {
					uni.navigateTo({
						url: '../login/login'
					})
				}
			})
			this.windowHeight = uni.getStorageSync("windowHeight")
			this.getUserData()
		},
		methods: {
			/**
			 * 获取用户所有设备
			 */
			getUserData() {
				this.$myRuquest({
					url: "/jsl/user/DeviceLocationById",
					data: {
						"requestParams": {
							"procedure": {
								"p_uid": this.$utils.getData("p_uid")
							}
						}
					}
				}).then(res => {
					this.userData = res
					this.$utils.setData('userdata', res)
					let resmarks = []; // 图标的集合
					res.forEach(item => {
						let mar = this.createMarker(item);
						resmarks.push(mar);
					})
					this.markers = resmarks
					this.getNowLocation()
				})
			},
			/**
			 * 获取当前位置
			 */
			getNowLocation() {
				if (this.markers.length) {
					this.centerX = this.markers[0].longitude
					this.centerY = this.markers[0].latitude
					// uni.createMapContext("map", this).moveToLocation({  
					// 	longitude: this.centerX,  
					// 	latitude: this.centerY
					// })
				} else {
					uni.getLocation({
						type: 'gcj02',
						success: (res) => {
							this.centerX = res.longitude
							this.centerY = res.latitude
							// uni.createMapContext("map", this).moveToLocation({  
							// 	longitude: this.centerX,  
							// 	latitude: this.centerY
							// })
						}
					})
				}
				if (getCurrentPages()[getCurrentPages().length - 1].route === 'pages/device-map/device-map') {
					setTimeout(() => {
						this.getUserData()
					}, 3000)
				}
			},
			toJSON() {},
			/**
			 * 还有地图标识，可以在name上面动手
			 */
			createMarker(point) {
				let latitude = point.latitude;
				let longitude = point.longitude;
				let marker = {
					iconPath: "../../static/images/dingwei.png",
					id: point.id || 0,
					name: point.name || '',
					latitude: latitude,
					longitude: longitude,
					width: 20,
					height: 32
				};
				return marker;
			}
		}
	}
</script>

<style>
</style>
